package com.oren.util;

import com.oren.annotation.Column;
import com.oren.annotation.Id;
import com.oren.annotation.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author wsw
 * @time 2018/7/10 21:01
 * @description 操作实体类的工具类
 * @Since jdk1.7
 */
public final class EntityUtil {


	private final static Logger LOGGER= LoggerFactory.getLogger(EntityUtil.class);

	/**
	 * 获取表名
	 * @param entity
	 * @return
	 */
	public static <T> String getTableName(T entity){
		String tableName="";
		if(entity.getClass().isAnnotationPresent(Table.class)){
			Table annotation=entity.getClass().getAnnotation(Table.class);
			if(annotation.value()==null || "".equals(annotation.value())){
				tableName=entity.getClass().getSimpleName();
			}else{
				tableName=annotation.value();
			}
		}else{
			LOGGER.error("entity"+ entity +"must have annotation for table ");
		}
		return tableName;
	}

	/**
	 * 根据实体类生成insert语句
	 * @param entity
	 * @param <T>
	 * @return
	 */
	public  static  <T> String  getInsertEntitySql(T entity){
		//获取所有的字段
		Field[] fieldArray = entity.getClass().getDeclaredFields();
		StringBuilder stringBuilder=new StringBuilder();
		stringBuilder.append("INSERT INTO ").append(getTableName(entity)).append(" ( ");
		StringBuilder values=new StringBuilder("( ");
		try {
			for (Field field:fieldArray) {
				Object fiedlValue = null;
				if(field.isAnnotationPresent(Id.class)){
					//设置可以访问
					field.setAccessible(true);
					Id annotation=field.getAnnotation(Id.class);
					//判断是否自增
					if(!annotation.increaseId()){
						fiedlValue=field.get(entity);
						String value=annotation.value();
						if(value==null || "".equals(value)){
							value=field.getName();
						}
						//判断字段的类型
						if(field.getType()==String.class){
							if(fiedlValue!=null && !"".equals(fiedlValue)){
								stringBuilder.append(value).append(" ,");
								values.append("'"+fiedlValue+"'").append(", ");
							}
						}else if(field.getType()==Integer.class || field.getType()==Long.class){
							if(fiedlValue!=null && !"".equals(fiedlValue)){
								stringBuilder.append(value).append(" ,");
								values.append(fiedlValue).append(", ");
							}
						}
					}
				}else if(field.isAnnotationPresent(Column.class)){
					field.setAccessible(true);
					Column columnAnnotation=field.getAnnotation(Column.class);
					fiedlValue=field.get(entity);
					String value=columnAnnotation.value();
					if(value==null || "".equals(value)){
						value=field.getName();
					}
					if(field.getType()==Integer.class || field.getType()==Long.class){
						if(fiedlValue!=null && !"".equals(fiedlValue)){
							stringBuilder.append(value).append(", ");
							values.append(fiedlValue).append(", ");
						}
					}else if(field.getType()== Date.class){
						if(fiedlValue!=null && !"".equals(fiedlValue)){
							stringBuilder.append(value).append(", ");
							values.append("'"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(fiedlValue)+"'").append(", ");
						}
					}
					else {
						if(fiedlValue!=null && !"".equals(fiedlValue)){
							stringBuilder.append(value).append(", ");
							values.append("'"+fiedlValue+"'").append(", ");
						}
					}
				}
			}
			stringBuilder.replace(stringBuilder.lastIndexOf(", "),stringBuilder.length() ,")");
			values.replace(values.lastIndexOf(", "),values.length() ,")");
			stringBuilder.append(" VALUES ").append(values);
			//System.out.println(stringBuilder.toString()+"======================");
			LOGGER.debug("生成的sql语句为:"+stringBuilder.toString());
		}catch (Exception e){
			e.printStackTrace();
		}
		return stringBuilder.toString();
	}

	/**
	 * 根据实体类生产update语句
	 * @param <T> 实体类
	 * @param columnStr where后面需要参数名称
	 * @return sql语句
	 */
	public static <T> String getUpdateEntitySql(T entity,String[] columnStr){

		Field[] fieldArray=entity.getClass().getDeclaredFields();
		StringBuilder stringBuilder=new StringBuilder(" UPDATE ").append(getTableName(entity)).append(" SET ");
		try {
			for (Field field:fieldArray) {
				Object value;
				field.setAccessible(true);
				int k=0;
				value=field.get(entity);
				boolean f=true;
				if(value!=null && !"".equals(value)){
					if(field.isAnnotationPresent(Column.class)){
						String fieldName=field.getAnnotation(Column.class).value();
						if(fieldName==null || "".equals(fieldName)){
							fieldName=field.getName();
						}
						if(columnStr!=null && columnStr.length>0){
							for (String column:columnStr) {
								if(column !=null && column.equals(fieldName)){
									f=false;
									break;
								}
							}
						}
						if(!f){
							continue;
						}
						if(k==0){
							if(field.getType()==Integer.class || field.getType()==Long.class || field.getType()==int.class){
								stringBuilder.append(" "+field.getName()).append(" = ").append(value).append(" , ");
							}else if(field.getType()==Date.class ){
								stringBuilder.append(" "+field.getName()).append(" = ").append("'"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value)+"'").append(" , ");
							}else{
								stringBuilder.append(" "+field.getName()).append(" = ").append("'"+value+"'").append(" , ");
							}
						}else {
							if(field.getType()==Integer.class || field.getType()==Long.class || field.getType()==int.class){
								stringBuilder.append(" "+field.getName()).append(" = ").append(value);
							}else if(field.getType()==Date.class ){
								stringBuilder.append(" "+field.getName()).append(" = ").append("'"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value)+"'");
							}else{
								stringBuilder.append(" "+field.getName()).append(" = ").append("'"+value+"'");
							}
						}

					}
				}
			}
		}catch (Exception e){
			LOGGER.debug("create updateSql failure",e);
		}
		stringBuilder.replace(stringBuilder.lastIndexOf(","),stringBuilder.length()," ");

		String sql=stringBuilder.append(getWhereAndSql(entity,columnStr)).toString();
		LOGGER.debug("生成的update语句为："+sql);
		return sql;
	}

	/**
	 *	根据实体类生成delete语句
	 * @param entity 实体类
	 * @param columnStr where后面需要参数名称
	 * @param <T> sql语句
	 * @return
	 */
	public static <T> String getDeleteEntitySql(T entity,String[] columnStr){
		StringBuilder stringBuilder=new StringBuilder("DELETE FROM ").append(getTableName(entity));

		String sql=stringBuilder.append(getWhereAndSql(entity,columnStr)).toString();
		LOGGER.debug("生成的delete 语句为："+sql);
		return sql;
	}

	/**
	 * 获取update和delete的条件语句
	 * @param entity 实体类
	 * @param columnStr 需要where语句参数名称
	 * @param <T>
	 * @return
	 */
	public static <T> StringBuilder getWhereAndSql(T entity,String[] columnStr){
		StringBuilder stringBuilder=new StringBuilder(" WHERE " );
		Field[] fields=entity.getClass().getDeclaredFields();
		boolean f=true;
		try {
			for (Field field:fields){
				field.setAccessible(true);
				Object value=field.get(entity);
				if(value!=null && !"".equals(value)){
					String filedName=field.getName();
					if(columnStr!=null && columnStr.length>0){
						for (int i = 0; i <columnStr.length; i++) {
							if(columnStr[i].equals(filedName)){
								if(field.getType()==String.class){
									stringBuilder.append(filedName).append(" = ").append("'"+value+"'").append(" and ");
								}else if(field.getType()==Integer.class || field.getType() == int.class || field.getType()==Long.class){
									stringBuilder.append(filedName).append(" = ").append(value).append(" and ");
								}
							}
						}
						f=false;
					}else{
						if(field.isAnnotationPresent(Id.class)){
							if(value!=null && !"".equals(value)){
								if(field.getType()==Integer.class || field.getType()==Long.class || field.getType()==int.class){
									String fieldName=field.getAnnotation(Id.class).value();
									if(fieldName!=null&&!"".equals(fieldName)){
										stringBuilder.append(" "+fieldName).append(" = ").append(value);
									}else{
										stringBuilder.append(" "+field.getName()).append(" = ").append(value);
									}
								}else{
									String fieldName=field.getAnnotation(Id.class).value();
									if(fieldName!=null&&!"".equals(fieldName)){
										stringBuilder.append(" "+fieldName).append(" = ").append(value);
									}else{
										stringBuilder.append(" "+field.getName()).append(" = ").append("'"+value+"'");
									}
								}
							}
						}
					}
				}
			}
			if(!f){
				stringBuilder.replace(stringBuilder.lastIndexOf("and"),stringBuilder.length()," ");
			}
		}catch (Exception e){
			LOGGER.debug("create sql failure",e);
		}
		return stringBuilder;
	}




}
